package org.jvm.classpath.entry;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

public class CompositeEntry implements Entry {

    private final List<Entry> entryList;

    public CompositeEntry(String paths) {
        //处理多地址情况
        if (paths.contains(Entry.pathListSeparator)) {
            this.entryList = Arrays.stream(paths.split(Entry.pathListSeparator))
                    .map(path -> EntryBuilder.newEntry(path))
                    .collect(Collectors.toList());
        }
        //处理通配符情况
        else if (paths.endsWith("*")) {
            this.entryList = buildByWildcard(paths);
        } else {
            this.entryList = new ArrayList<>();
        }
    }

    private List<Entry> buildByWildcard(String paths) {
        File file = new File(paths.substring(0, paths.length() - 1));
        return Arrays.stream(file.listFiles())
                .filter(item -> !item.isDirectory() && item.getName().toLowerCase().endsWith(".jar"))
                .map(item -> new ZipEntry(item.getAbsolutePath()))
                .collect(Collectors.toList());
    }

    public CompositeEntry() {
        this.entryList = new ArrayList<>();
    }

    @Override
    public byte[] readClass(String className) {
        for (Entry entry : entryList) {
            byte[] klass = entry.readClass(className);
            if (klass != null) {
                return klass;
            }
        }
        return null;
    }

    @Override
    public String getPath() {
        if (entryList == null || entryList.size() == 0) {
            return "";
        }
        String result = "";
        for (Entry entry : entryList) {
            result = result + entry.getPath() + Entry.pathListSeparator;
        }
        return result.substring(0, result.length() - 1);
    }
}
